<?php
/**
 * Created by : PhpStorm
 * Index: 阿城 <479468212@qq.com>
 * Date: 2019/12/27
 * Time: 13:02
 */

namespace app\admin\controller\article;

use app\admin\controller\Base;
use app\common\model\CommonArticle as articleModel;
use app\common\model\CommonArticleCategory as categoryModel;
use think\exception\ValidateException;
use think\facade\Db;
use app\util\Tools;


class Index extends Base
{
    /**
     * @OA\Get(
     *   path="/admin/Article/index",
     *   tags={"文章相关"},
     *   summary="文章列表",
     *   description="文章管理",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(ref="#/components/parameters/keywords"),
     *   @OA\Parameter(name="category_id",in="query",description="分类ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Parameter(ref="#/components/parameters/order"),
     *   @OA\Parameter(ref="#/components/parameters/size"),
     *   @OA\Parameter(ref="#/components/parameters/page"),
     *   @OA\Response(
     *     response="200",
     *     description="返回JSON",
     *     @OA\MediaType(
     *      mediaType="application/json",
     *      @OA\Schema(
     *         @OA\Property(property="code", type="number",description="状态码"),
     *         @OA\Property(property="msg", type="string",description="提示消息"),
     *         @OA\Property(property="data", type="object",description="数据列表",@OA\Items),
     *      )
     *    )
     *   ),
     *   @OA\Response(response="500", description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function index()
    {
        $limit       = $this->request->get('size', config('easyApi.ADMIN_LIST_DEFAULT'));
        $start       = $this->request->get('page', 1);
        $keywords    = $this->request->get('keywords');
        $order       = $this->request->get('order','create_time DESC');
        $category_id = $this->request->get('category_id');
        //取分类
        $categoryModel= new categoryModel();
        $categoryList = $categoryModel->field('id,name as title,parent_id,parent_path')->order('id desc')->select()->toArray();
        $categoryTree = [];
        $cascaderData = [];
        if(!empty($categoryList)){
            $categoryTree = Tools::listToTree($categoryList,'id','parent_id','children');
            $listCategoryData = $categoryModel->field('id as value,name as label,parent_id')->select()->toArray();
            $cascaderData = Tools::listToTree($listCategoryData,'value','parent_id','children');
        }
        //取文章
        $articleModel = new articleModel();
        if(!empty($category_id)){
            $articleIdArr = Db::name('common_article_category_rel')->where(['category_id'=>$category_id])->column('article_id');
            $articleModel = $articleModel->where('id','in',$articleIdArr);
        }
        if (!empty($keywords)) {
            $articleModel = $articleModel->where('title like "%'.$keywords.'%"');
        }
        $listObj = $articleModel->order($order)->paginate($limit, false, ['page' => $start])->toArray();
        $this->success('获取文章成功',[
            'cascader_data' => $cascaderData,
            'category_tree' => $categoryTree,
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    /**
     * @OA\Post(
     *   path="/admin/Article/add",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   tags={"文章相关"},
     *   summary="添加文章",
     *   @OA\RequestBody(
     *      @OA\MediaType(
     *         mediaType="application/json",
     *         @OA\Schema(
     *            @OA\Property(property="title", type="string", description="标题"),
     *            @OA\Property(property="keywords", type="string", description="关键字"),
     *            @OA\Property(property="excerpt", type="string", description="摘要"),
     *            @OA\Property(property="source", type="string", description="来源"),
     *            @OA\Property(property="thumbnail", type="string", description="缩略图"),
     *            @OA\Property(property="content", type="string", description="内容"),
     *            example={"category_id":"1,2","title": "面朝大海，春暖花开", "keywords": "面朝大海，春暖花开","excerpt":"从明天起，做一个幸福的人。喂马，劈柴，周游世界。从明天起，关心粮食和蔬菜。我有一所房子，面朝大海，春暖花开","source":null,"thumbnail":"default/20200115\8dc528f33648e5d782d0a3f7daacefe0.jpg","content":"从明天起，做一个幸福的人。喂马，劈柴，周游世界。从明天起，关心粮食和蔬菜。我有一所房子，面朝大海，春暖花开……"}
     *         )
     *       )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK",
     *         @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *     ),
     *     @OA\Response(response="500", description="服务器错误"),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function add() {
        $postData = $this->request->post();
        $validateRule =   [
            'title'        => 'require',
            'category_id'  => 'require',
            'excerpt'      => 'min:10',
            'content'      => 'require|min:10',
        ];
        $validateMsg  =   [
            'title.require'      => '标题必须',
            'content.require'    => '内容必须',
            'category_id.require'=> '分类必选',
            'excerpt.min'        => '摘要不能少于10个字',
            'content.min'        => '内容不能少于10个字',
        ];
        try {
            validate($validateRule,$validateMsg)->check($postData);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $postData['uid'] = $this->userId;
        $articleModel = new articleModel();
        $find = $articleModel->where(['title'=>$postData['title']])->order('create_time desc')->find();
        if(!empty($find)){
            $this->error("文章重复");
        }
        $categoryIdArr = explode(',', $postData['category_id']);
        if(empty($categoryIdArr)){
            $this->error("分类参数不正确");
        }
        $articleModel->startTrans();
        $result = $articleModel->create($postData);
        if (!$result) {
            $this->error();
        }
        $articleID = $articleModel->getLastInsID();
        $relData = [];
        foreach ($categoryIdArr as $val){
            if(empty(categoryModel::find($val))){
                $articleModel->rollback();
                $this->error("分类不存在：$val");
            }
            $relData[] = ['article_id'=>$articleID,'category_id'=>$val];
        }
        $result = Db::name('common_article_category_rel')->insertAll($relData);
        if (!$result) {
            $articleModel->rollback();
            $this->error();
        }
        $articleModel->commit();
        $this->success();
    }

    /**
     * @OA\Put(
     *   path="/admin/Article/edit/{id}",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="文章ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   tags={"文章相关"},
     *   summary="编辑文章",
     *   @OA\RequestBody(
     *      @OA\MediaType(
     *         mediaType="application/json",
     *         @OA\Schema(
     *            @OA\Property(property="title", type="string", description="标题"),
     *            @OA\Property(property="keywords", type="string", description="关键字"),
     *            @OA\Property(property="excerpt", type="string", description="摘要"),
     *            @OA\Property(property="source", type="string", description="来源"),
     *            @OA\Property(property="thumbnail", type="string", description="缩略图"),
     *            @OA\Property(property="content", type="string", description="内容"),
     *            example={"category_id":"1,2","title": "面朝大海，春暖花开", "keywords": "面朝大海，春暖花开","excerpt":"从明天起，做一个幸福的人。喂马，劈柴，周游世界。从明天起，关心粮食和蔬菜。我有一所房子，面朝大海，春暖花开","source":null,"thumbnail":"default/20200115\8dc528f33648e5d782d0a3f7daacefe0.jpg","content":"从明天起，做一个幸福的人。喂马，劈柴，周游世界。从明天起，关心粮食和蔬菜。我有一所房子，面朝大海，春暖花开……"}
     *         )
     *       )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK",
     *         @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *     ),
     *     @OA\Response(response="500", description="服务器错误"),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function edit($id) {
        $postData = $this->request->post();
        $postData['id'] = $id;
        $validateRule =   [
            'id'           => 'require',
            'title'        => 'require',
            'category_id'  => 'require',
            'excerpt'      => 'min:10',
            'content'      => 'require|min:10',
        ];
        $validateMsg  =   [
            'id.require'         => 'ID必填',
            'title.require'      => '标题必须',
            'content.require'    => '内容必须',
            'category_id.require'=> '分类必选',
            'excerpt.min'        => '摘要不能少于10个字',
            'content.min'        => '内容不能少于10个字',
        ];
        try {
            validate($validateRule,$validateMsg)->check($postData);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $articleModel = new articleModel();
        $find = $articleModel->find($postData['id']);
        if(empty($find)){
            $this->error("无效参数");
        }
        $categoryIdArr = explode(',', $postData['category_id']);
        if(empty($categoryIdArr)){
            $this->error("分类参数不正确");
        }
        $existedCategoryId = Db::name('common_article_category_rel')->where(['article_id'=>$postData['id']])->column('category_id');
        $intersectCategory = array_intersect($categoryIdArr,$existedCategoryId);
        Db::startTrans();
        $articleModel->startTrans();
        //删除取消的分类
        Db::name('common_article_category_rel')->where('category_id','not in',$categoryIdArr)->where(['article_id'=>$postData['id']])->delete();
        $relData = [];
        foreach ($categoryIdArr as $val){
            //已存在不添加
            if(in_array($val,$intersectCategory)){
                continue;
            }
            if(empty(categoryModel::find($val))){
                $articleModel->rollback();
                $this->error("分类不存在：$val");
            }
            $relData[] = ['article_id'=>$postData['id'],'category_id'=>$val];
        }
        $result = Db::name('common_article_category_rel')->insertAll($relData);
        if ($result===false) {
            $articleModel->rollback();
            Db::rollback();
            $this->error();
        }
        unset($postData['category_id']);
        $result = $articleModel->update($postData);
        if ($result===false) {
            $articleModel->rollback();
            Db::rollback();
            $this->error('更新失败');
        }
        $articleModel->commit();
        Db::commit();
        $this->success();
    }

    /**
     * @OA\Put(path="/admin/Article/changeStatus/{id}",
     *   tags={"文章相关"},
     *   summary="变更文章状态",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="文章ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Parameter(name="status",in="query",required=true,description="状态。0未发布，1已发布",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function changeStatus($id) {
        $status = $this->request->param('status');
        if(!$id){
            $this->error('参数错误');
        }
        $res = articleModel::update([
            'id'     => $id,
            'status' => $status
        ]);
        if ($res === false) {
            $this->error();
        } else {
            $this->success();
        }
    }

    /**
     * @OA\Put(path="/admin/Article/changeSort/{id}",
     *   tags={"文章相关"},
     *   summary="文章排序",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="文章ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Parameter(name="value",in="query",required=true,description="排序值",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function changeSort($id) {
        $value = $this->request->param('value');
        if(!$id){
            $this->error('参数错误');
        }
        $res = articleModel::update([
            'id'     => $id,
            'sort' => $value
        ]);
        if ($res === false) {
            $this->error();
        } else {
            $this->success();
        }
    }

    /**
     * @OA\Put(path="/admin/Article/changeTop/{id}",
     *   tags={"文章相关"},
     *   summary="变更文章置顶",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="文章ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Parameter(name="status",in="query",required=true,description="状态。0未置顶，1已置顶",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function changeTop($id) {
        $top = $this->request->param('top');
        if(!$id){
            $this->error('参数错误');
        }
        $res = articleModel::update([
            'id'     => $id,
            'top' => $top
        ]);
        if ($res === false) {
            $this->error();
        } else {
            $this->success();
        }
    }

    /**
     * @OA\Put(path="/admin/Article/changeRecommend/{id}",
     *   tags={"文章相关"},
     *   summary="变更文章推荐",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="文章ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Parameter(name="status",in="query",required=true,description="状态。0未推荐，1已推荐",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function changeRecommend($id) {
        $recommend = $this->request->param('recommend');
        if(!$id){
            $this->error('参数错误');
        }
        $res = articleModel::update([
            'id'     => $id,
            'recommend' => $recommend
        ]);
        if ($res === false) {
            $this->error();
        } else {
            $this->success();
        }
    }

    /**
     * @OA\Delete(path="/admin/Article/delete/{id}",
     *   tags={"文章相关"},
     *   summary="删除文章",
     *   description="删除指定文章",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="id",in="path",required=true,description="文章ID",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function delete($id) {
        if(!$id){
            $this->error('参数未填');
        }
        $articleModel = new articleModel();
        Db::startTrans();
        $articleModel->startTrans();
        Db::name('common_article_category_rel')->where(['article_id' => $id])->delete();
        $result = $articleModel->destroy(['id'=>$id]);
        if(!$result){
            $articleModel->rollback();
            Db::rollback();
            $this->error();
        }
        $articleModel->commit();
        Db::commit();
        $this->success();
    }
}
